<!DOCTYPE html>
<html>
<head>
    <script src="https://unpkg.com/plantuml-encoder@1.4.0/dist/plantuml-encoder.min.js"></script>
</head>
<body>
<div id="uml-diagram" style="position:relative"></div>

<script>
    const plantUmlCode = `
            @startuml architecture

            node "API Gateway" as api #lightblue
            node "User Service" as user #lightgreen
            node "Order Service" as order #lightyellow
            node "Database" as db #lightgray

            api --> user : HTTP
            api --> order : HTTP
            user --> db : SQL
            order --> db : SQL

            note right of api : 示例架构图\\n点击节点查看功能

            @enduml
`;

    // 编码为 URL 可用格式
    const encoded = plantumlEncoder.encode(plantUmlCode);
    const svgUrl = `https://www.plantuml.com/plantuml/svg/${encoded}`;

    // 加载 SVG
    fetch(svgUrl)
        .then(response => response.text())
        .then(svgText => {
            const parser = new DOMParser();
            const svgDoc = parser.parseFromString(svgText, "image/svg+xml");
            const svgElement = svgDoc.documentElement;

            // 添加交互功能
            enhanceDiagram(svgElement);

            // 挂载到页面
            document.getElementById('uml-diagram').appendChild(svgElement);
        });

    // 增强图表功能
    function enhanceDiagram(svg) {
        // 1. 添加点击事件
        const classes = svg.querySelectorAll('[class*="class"], text');
        classes.forEach(el => {
            el.style.cursor = 'pointer';
            el.addEventListener('click', (e) => {
                const className = e.target.textContent.trim();
                alert(`Clicked on class: ${className}`);
                e.target.style.fill = 'red';
            });
        });

        // 2. 添加悬停效果
        const relations = svg.querySelectorAll('path, polygon');
        relations.forEach(line => {
            line.addEventListener('mouseover', () => line.style.stroke = 'blue');
            line.addEventListener('mouseout', () => line.style.stroke = '');
        });

        // 3. 插入自定义控件
        const customBtn = document.createElement('div');
        customBtn.innerHTML = `<button style="position:absolute; top:10px; left:10px; z-index:100">
        自定义按钮
      </button>`;
        customBtn.onclick = () => alert('自定义事件!');
        document.getElementById('uml-diagram').appendChild(customBtn);
    }
</script>
</body>
</html>
